import { IPrintViewProps, PrintViewParamType } from '@/common/types/printView';
import { useThirdParty } from '@/components/thirdParty/hooks';

export const useOnlyOffice = (props: IPrintViewProps) => {
  const isReady = ref(false);
  const documentServerUrl = process.env.VUE_APP_ONLYOFFICE_SERVER || '';
  const { thirdParams, onCloseThirdDialog } = useThirdParty(props);

  console.log('props', props);

  const dialogParams = computed(() => {
    return {
      printId: props.printId || thirdParams.value.printId,
      printName: props.printName || thirdParams.value.printName,
      paramList: props.printParam || thirdParams.value.printParam || [],
    };
  });

  const printParamList = computed<PrintViewParamType[]>(() => {
    if (Array.isArray(dialogParams.value.paramList)) {
      return dialogParams.value.paramList.map(item => {
        return {
          paramName: item.paramName,
          paramValue: item.paramValue,
        };
      });
    } else {
      return [];
    }
  });

  const onDocumentReady = () => {
    console.log('文档加载完成');
  };

  const onError = err => {
    console.log('Error loading editor: ', err);
  };
  const onLoadComponentError = (errorCode, errorDescription) => {
    console.log('Error loading component: ' + errorDescription, 'errorCode', errorCode);
    switch (errorCode) {
      case -1: // Unknown error loading component
        console.log(errorDescription);
        break;

      case -2: // Error load DocsAPI from http://documentserver/
        console.log(errorDescription);
        break;

      case -3: // DocsAPI is not defined
        console.log(errorDescription);
        break;
    }
  };

  // 修改消息监听器，添加更多调试信息
  const messageHandler = event => {
    // 打印所有收到的消息
    console.log('收到消息:', event);
  };

  onMounted(() => {
    window.addEventListener('message', messageHandler);
  });

  onUnmounted(() => {
    window.removeEventListener('message', messageHandler);
  });

  return {
    isReady,
    documentServerUrl,
    printParamList,
    onCloseThirdDialog,
    onDocumentReady,
    onError,
    onLoadComponentError,
  };
};
